package com.zzw.limit.component.aspect;

import com.zzw.limit.alg.handler.LimitHandler;
import com.zzw.limit.component.anotation.Limit;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletResponse;

import java.lang.reflect.Method;

@Aspect
@Component
public class LimitAspect {

    @Autowired
    private LimitHandler limitHandler;

    @Autowired
    private HttpServletResponse response;

    @Pointcut("@annotation(com.zzw.limit.component.anotation.Limit)")
    public void pt(){}

    //环绕通知
    @Around("pt()")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Limit limit = method.getAnnotation(Limit.class);
        Boolean flag = limitHandler.isLimit(limit);
        if (!flag){
            response.setStatus(429);
            return "Too Many Requests";
        }
        //执行方法
        Object result = joinPoint.proceed();
        return result;
    }
}
